package com.management.department.teacherinfosystem.Controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.management.department.teacherinfosystem.DTO.*;
import com.management.department.teacherinfosystem.Entity.*;
import com.management.department.teacherinfosystem.Repository.*;
import com.management.department.teacherinfosystem.Service.ResearchProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@RestController
@RequestMapping("/api/research-projects")
@CrossOrigin(origins = "*")
public class ResearchProjectController {

    @Autowired
    private ResearchProjectRepository projectRepository;
    @Autowired
    private ResearchProjectMemberRepository memberRepository;
    @Autowired
    private ResearchProjectFundingRepository fundingRepository;
    @Autowired
    private AttachmentRepository attachmentRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ResearchProjectService projectService;

    // 获取所有科研项目（包含经费总额）
    @GetMapping
    public List<Map<String, Object>> getAllProjects() {
        List<ResearchProject> projects = projectRepository.findAll();
        List<Map<String, Object>> projectsWithFunding = new ArrayList<>();
        
        for (ResearchProject project : projects) {
            // 计算经费总额
            List<ResearchProjectFunding> fundings = fundingRepository.findByProjectId(project.getId());
            double totalFunding = fundings.stream()
                    .mapToDouble(f -> f.getAmount().doubleValue())
                    .sum();
            
            // 获取负责人姓名
            String leaderName = "";
            if (project.getLeaderId() != null) {
                var leader = userRepository.findById(project.getLeaderId());
                if (leader.isPresent()) {
                    leaderName = leader.get().getName();
                }
            }
            
            // 构建包含经费总额的项目数据
            Map<String, Object> projectData = new HashMap<>();
            projectData.put("id", project.getId());
            projectData.put("name", project.getName());
            projectData.put("projectNumber", project.getProjectNumber());
            projectData.put("projectType", project.getProjectType());
            projectData.put("subjectCategory", project.getSubjectCategory());
            projectData.put("level", project.getLevel());
            projectData.put("sourceUnit", project.getSourceUnit());
            projectData.put("leaderId", project.getLeaderId());
            projectData.put("leaderName", leaderName); // 添加负责人姓名
            projectData.put("status", project.getStatus());
            projectData.put("applicationDate", project.getApplicationDate());
            projectData.put("startDate", project.getStartDate());
            projectData.put("endDate", project.getEndDate());
            projectData.put("totalFunding", totalFunding);
            projectData.put("fundingSource", project.getFundingSource());
            projectData.put("fundingStatus", project.getFundingStatus());
            projectData.put("createdAt", project.getCreatedAt());
            projectData.put("updatedAt", project.getUpdatedAt());
            projectData.put("description", project.getDescription());
            
            projectsWithFunding.add(projectData);
        }
        
        return projectsWithFunding;
    }

    // 根据状态获取项目
    @GetMapping("/by-status/{status}")
    public List<ResearchProject> getProjectsByStatus(@PathVariable("status") String status) {
        return projectRepository.findByStatus(status);
    }

    // 获取待审核项目
    @GetMapping("/pending-review")
    @PreAuthorize("hasRole('ADMIN')")
    public List<ResearchProject> getPendingReviewProjects() {
        return projectRepository.findPendingReviewProjects();
    }

    // 创建科研项目
    @PostMapping
    public ResponseEntity<?> createProject(
            @RequestPart("data") String data,
            @RequestPart(value = "files", required = false) MultipartFile[] files
    ) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        ResearchProjectSubmitDTO dto = mapper.readValue(data, ResearchProjectSubmitDTO.class);

        Long projectId = projectService.saveProjectWithMembersAndFile(dto, files);
        return ResponseEntity.ok(Map.of("message", "科研项目创建成功！", "projectId", projectId));
    }

    // 查询项目详情（含成员、附件、经费）
    @GetMapping("/{id:[0-9]+}")
    public Map<String, Object> getProjectDetail(@PathVariable("id") Long id) {
        ResearchProject project = projectRepository.findById(id).orElse(null);
        List<ResearchProjectMember> members = memberRepository.findByProjectId(id);
        
        // 组装每个成员的姓名/工号/部门
        for (ResearchProjectMember m : members) {
            if (m.getUserId() != null) {
                User u = userRepository.findById(m.getUserId()).orElse(null);
                if (u != null) {
                    m.setName(u.getName());
                    m.setStaffNo(u.getStaffNo());
                    m.setDepartment(u.getDepartment());
                }
            }
        }

        // 负责人姓名补全
        String leaderName = null;
        if (project != null && project.getLeaderId() != null) {
            User leader = userRepository.findById(project.getLeaderId()).orElse(null);
            if (leader != null) {
                leaderName = leader.getName();
            }
        }

        // 获取经费信息
        List<ResearchProjectFunding> fundings = fundingRepository.findByProjectId(id);
        double totalFunding = fundings.stream()
                .mapToDouble(f -> f.getAmount().doubleValue())
                .sum();

        List<Attachment> attachments = attachmentRepository.findByRelatedTypeAndRelatedId("research_project", id);
        List<Attachment> finishAttachments = attachmentRepository.findByRelatedTypeAndRelatedId("research_project_finish", id);
        
        return Map.of(
                "project", project,
                "leaderName", leaderName,
                "members", members,
                "fundings", fundings,
                "totalFunding", totalFunding,
                "attachments", attachments,
                "finishAttachments", finishAttachments
        );
    }

    // 审核科研项目
    @PostMapping("/{id:[0-9]+}/review")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> reviewProject(
            @PathVariable("id") Long id,
            @RequestBody ReviewDTO reviewDTO
    ) {
        ResearchProject project = projectRepository.findById(id).orElse(null);
        if (project == null) {
            return ResponseEntity.notFound().build();
        }

        // 获取当前用户
        org.springframework.security.core.Authentication auth = 
            org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = auth.getName();
        User reviewer = userRepository.findByUsername(currentUsername).orElse(null);
        if (reviewer == null) {
            return ResponseEntity.badRequest().body("审核人信息不存在");
        }

        // 判断是否为结题审核：检查项目是否有结题信息
        boolean isFinishReview = "结题审核中".equals(project.getStatus()) 
                                || (project.getFinishDate() != null)
                                || (project.getFinishType() != null && !project.getFinishType().trim().isEmpty());
        
        if (isFinishReview) {
            // 结题审核，记录到结题审核意见字段
            project.setFinishReviewOpinion(reviewDTO.getOpinion());
            project.setFinishReviewerId(reviewer.getId());
            project.setFinishReviewTime(new Date());
        } else {
            // 申报审核，记录到申报审核意见字段
            project.setReviewOpinion(reviewDTO.getOpinion());
            project.setReviewerId(reviewer.getId());
            project.setReviewTime(new Date());
        }

        // 根据审核结果进行状态流转
        if ("已通过".equals(reviewDTO.getStatus())) {
            if ("申报中".equals(project.getStatus())) {
                project.setStatus("已立项");
                project.setApprovalDate(new Date());
            } else if ("结题审核中".equals(project.getStatus())) {
                project.setStatus("已结题");
            }
        } else if ("已驳回".equals(reviewDTO.getStatus())) {
            project.setStatus("已驳回");
        }
        
        project.setUpdatedAt(new Date());
        projectRepository.save(project);
        
        return ResponseEntity.ok("审核完成");
    }

    // 获取我的科研项目
    @GetMapping("/my")
    public List<Map<String, Object>> getMyProjects(@RequestParam("userId") Long userId) {
        List<ResearchProject> projects = projectRepository.findProjectsByUserId(userId);
        List<Map<String, Object>> projectsWithFunding = new ArrayList<>();
        
        for (ResearchProject project : projects) {
            // 计算经费总额
            List<ResearchProjectFunding> fundings = fundingRepository.findByProjectId(project.getId());
            double totalFunding = fundings.stream()
                    .mapToDouble(f -> f.getAmount().doubleValue())
                    .sum();
            
            // 获取负责人姓名
            String leaderName = "";
            if (project.getLeaderId() != null) {
                var leader = userRepository.findById(project.getLeaderId());
                if (leader.isPresent()) {
                    leaderName = leader.get().getName();
                }
            }
            
            // 构建包含经费总额的项目数据
            Map<String, Object> projectData = new HashMap<>();
            projectData.put("id", project.getId());
            projectData.put("name", project.getName());
            projectData.put("projectNumber", project.getProjectNumber());
            projectData.put("projectType", project.getProjectType());
            projectData.put("subjectCategory", project.getSubjectCategory());
            projectData.put("level", project.getLevel());
            projectData.put("sourceUnit", project.getSourceUnit());
            projectData.put("leaderId", project.getLeaderId());
            projectData.put("leaderName", leaderName); // 添加负责人姓名
            projectData.put("status", project.getStatus());
            projectData.put("applicationDate", project.getApplicationDate());
            projectData.put("startDate", project.getStartDate());
            projectData.put("endDate", project.getEndDate());
            projectData.put("totalFunding", totalFunding);
            projectData.put("fundingSource", project.getFundingSource());
            projectData.put("fundingStatus", project.getFundingStatus());
            projectData.put("createdAt", project.getCreatedAt());
            projectData.put("updatedAt", project.getUpdatedAt());
            projectData.put("description", project.getDescription());
            
            projectsWithFunding.add(projectData);
        }
        
        return projectsWithFunding;
    }

    // 重新提交科研项目
    @PostMapping("/{id:[0-9]+}/resubmit")
    public ResponseEntity<?> resubmitProject(
            @PathVariable("id") Long id,
            @RequestPart("data") String data,
            @RequestPart(value = "files", required = false) MultipartFile[] files
    ) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        ResearchProjectSubmitDTO dto = mapper.readValue(data, ResearchProjectSubmitDTO.class);

        projectService.resubmitProject(id, dto, files);
        return ResponseEntity.ok("重新提交成功！");
    }

    // 开始执行项目（立项后转为执行中）
    @PostMapping("/{id:[0-9]+}/start-execution")
    public ResponseEntity<?> startProjectExecution(@PathVariable("id") Long id) {
        ResearchProject project = projectRepository.findById(id).orElse(null);
        if (project == null) {
            return ResponseEntity.notFound().build();
        }
        
        if (!"已立项".equals(project.getStatus())) {
            return ResponseEntity.badRequest().body("只有已立项的项目才能开始执行");
        }
        
        project.setStatus("执行中");
        project.setUpdatedAt(new Date());
        projectRepository.save(project);
        
        return ResponseEntity.ok("项目已开始执行");
    }

    // 提交结题材料
    @PostMapping("/{id:[0-9]+}/finish")
    public ResponseEntity<?> submitFinishMaterials(
            @PathVariable("id") Long id,
            @RequestPart("data") String data,
            @RequestPart(value = "files", required = false) MultipartFile[] files
    ) throws Exception {
        ResearchProject project = projectRepository.findById(id).orElse(null);
        if (project == null) {
            return ResponseEntity.notFound().build();
        }

        ObjectMapper mapper = new ObjectMapper();
        ResearchFinishDTO dto = mapper.readValue(data, ResearchFinishDTO.class);

        projectService.submitFinishMaterials(id, dto, files);
        return ResponseEntity.ok("结题材料提交成功");
    }

    // 删除科研项目
    @DeleteMapping("/{id:[0-9]+}")
    public ResponseEntity<?> deleteProject(@PathVariable("id") Long id) {
        try {
            ResearchProject project = projectRepository.findById(id).orElse(null);
            if (project == null) {
                return ResponseEntity.notFound().build();
            }

            // 获取当前登录用户
            org.springframework.security.core.Authentication auth = 
                org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
            String currentUsername = auth.getName();
            User currentUser = userRepository.findByUsernameWithRoles(currentUsername).orElse(null);
            
            if (currentUser == null) {
                return ResponseEntity.status(401).body("用户未登录");
            }

            // 检查权限：只有项目负责人或管理员可以删除
            boolean isAdmin = currentUser.getUserRoles().stream()
                .anyMatch(userRole -> "admin".equals(userRole.getRole().getName()));
            boolean isProjectLeader = project.getLeaderId().equals(currentUser.getId());

            if (!isAdmin && !isProjectLeader) {
                return ResponseEntity.status(403).body("权限不足，只有项目负责人或管理员可以删除项目");
            }

            // 检查项目状态：只能删除申报中或已驳回的项目
            if (!"申报中".equals(project.getStatus()) && !"已驳回".equals(project.getStatus())) {
                return ResponseEntity.badRequest().body("只能删除申报中或已驳回的项目");
            }

            // 调用Service层删除方法（有事务支持）
            projectService.deleteProject(id);
            
            return ResponseEntity.ok("项目删除成功");
            
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("删除失败：" + e.getMessage());
        }
    }

    // 根据项目类型查询
    @GetMapping("/by-type/{type}")
    public List<ResearchProject> getProjectsByType(@PathVariable("type") String type) {
        return projectRepository.findByProjectType(type);
    }

    // 根据学科分类查询
    @GetMapping("/by-subject/{subject}")
    public List<ResearchProject> getProjectsBySubject(@PathVariable("subject") String subject) {
        return projectRepository.findBySubjectCategory(subject);
    }

    // 根据项目级别查询
    @GetMapping("/by-level/{level}")
    public List<ResearchProject> getProjectsByLevel(@PathVariable("level") String level) {
        return projectRepository.findByLevel(level);
    }

    // 搜索项目（按名称）
    @GetMapping("/search")
    public List<ResearchProject> searchProjects(@RequestParam("keyword") String keyword) {
        return projectRepository.findByNameContaining(keyword);
    }

    // 根据工号查询用户信息（用于成员自动填充）
    @GetMapping("/check")
    public Map<String, Object> checkUserByStaffNo(@RequestParam("staffNo") String staffNo) {
        var opt = userRepository.findByStaffNo(staffNo.trim());
        boolean exist = opt.isPresent();
        if (exist) {
            User u = opt.get();
            return Map.of(
                    "exist", true,
                    "name", u.getName(),
                    "department", u.getDepartment(),
                    "userId", u.getId()
            );
        }
        return Map.of("exist", false);
    }
}
